import urlConfig from './common.js'
import auth from '../util/auth.js'
import setting from '../util/setting.js'
import aes from '../util/aes.js'

const request = {}
const headers = {}
const PORT1 = '/baseinfo'
request.PUBLIC = 'public'
request.GUEST = 'guest'

request.USER = 'user'
request.ADMIN = 'admin'
request.post = (url, method, data, power) => {
	uni.onNetworkStatusChange(function (res) {
	    console.log(res.isConnected);//当前是否有网络连接
	    console.log(res.networkType);//网络类型
	    if(res.isConnected === false){
	        console.log("当前无网络");
			return {
				status:101,
				"msg":"网络太差了"
			}
	    }
	});
/*     权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分
    1 == 不通过access_token校验的接口
    2 == 文件下载接口列表
    3 == 验证码登录 */
	let accessToken = ""
	try {
		accessToken = auth.getToken()
	} catch (e) {
		console.log("出错了..",e);
	}
    headers['Accept'] = "application/json"
    headers['App-Key'] = setting.getAppKey()
    headers['App-Sign'] = setting.getSign()
    switch (power){
        case request.ADMIN:
        case request.USER:
			if(accessToken == ""){
			}
            headers['Authorization'] = 'Bearer '+accessToken
            break;
        case request.GUEST:
			if(accessToken != ""){
			}
            break;
    }
    return uni.request({
        url: url,
        method,
        data: data,
        dataType: 'json',
        header: headers
    }).then(res => {
        if (res[1].data.status && res[1].data.code == 200) {
            return res[1]
        } else {
            throw res[1].data
        }
    }).catch(parmas => {
　　　　　　switch (parmas.code) {
　　　　　　　　case 401:
　　　　　　　　　　uni.clearStorageSync()
　　　　　　　　　　break
　　　　　　　　default:
　　　　　　　　　　uni.showToast({
　　　　　　　　　　　　title: "testes",
　　　　　　　　　　　　icon: 'none'
　　　　　　　　　　})
　　　　　　　　　　return Promise.reject()
　　　　　　　　　　break
　　　　　　}

　　})
 } 
request.globalRequest = (url, method, data, power,baseUri) => {
	let resultData = false
	let allowedCached = false;
	try{
		allowedCached = data.hasOwnProperty('cacheTime')
	}catch(err){
		
	}
	let cacheTime = 0
	try{
		if(data.hasOwnProperty('cacheTime')){
			cacheTime = data['cacheTime'];
		}
	}catch(err){
		
	}
	if(allowedCached){
		resultData = uni.getStorageSync('page_data')
	}
	headers['Accept'] = "application/json"
    headers['App-Key'] = setting.getAppKey()
    headers['App-Sign'] = setting.getSign()
	let accessToken = ""
	try {
		accessToken = auth.getToken()
	} catch (e) {
		console.log("出错了..",e);
	}
    switch (power){
        case request.ADMIN:
        case request.USER:
            headers['Authorization'] = 'Bearer '+accessToken
            break;
        case request.GUEST:
			if(accessToken != ""){
				uni.switchTab({
					url:setting.getHomePage()
				})
			}
            break;
    }
	if(url.indexOf('http://') == -1 && url.indexOf('https://') == -1){
		if(baseUri == undefined ||  baseUri == "string" && baseUri == ""){
			url = urlConfig + url
		}else{
			url = baseUri + url
		}
	}
	console.log(url)
            
    let uniRequestData = uni.request({
        url: url,
        method,
        data: data,
        dataType: 'json',
        header: headers
    }).then(response => {
	   //console.log(urlConfig+url,res,method)
	   if(response.statusCode == 500 || response.statusCode == 404 || response.statusCode == 403){
		   let responseData = {
			   status:500,
			   msg:"接口访问失败",
			   debug:response.data
		   }
		   if(setting.getDebug()){
			   console.log(url,response.data)
		   }
		   return responseData
	   }
	   //console.log(JSON.stringify(res))
	   if(response.statusCode == 401 || response.statusCode == '401 Unauthorized'){
		   let removeFailed = auth.removeToken()
		   //return JSON.parse('{"status":401,"message":"未登录"}')
		   console.log("移除用户",removeFailed)
		   // 获取当前页面实例
		   const pages = getCurrentPages();
		   // 获取当前页面的实例
		   const currentPage = pages[pages.length - 1];
		   window.localStorage.setItem('prevUrl',currentPage.route);
		   uni.redirectTo({
			url:setting.getLoginPage(),
			fail(res) {
				console.log(res)
			}
		   })
	   }
	   let errorMsg = "";
	   if(response[0] != null){
		   if(response[0].hasOwnProperty('errMsg')){
				errorMsg = response[0]["errMsg"]
		   }
		   
	   }
	   if(errorMsg != "request:fail abort statusCode:-1"){
			let responseData = aes.decrypt(response.data)
			try{
				responseData = JSON.parse(responseData)
			}catch(e){
				//TODO handle the exception
				console.log(response.data)
				console.log("解密失败")
			}
			console.log(responseData)
		
		   if(responseData.status == 401 || responseData.status == 419){
			   let removeFailed = auth.removeToken()
				return JSON.parse('{"status":401,"message":"未登录"}')
			   uni.redirectTo({
				url:setting.getLoginPage(),
				fail(res) {
					console.log(res)
				}
			   })
			   
		   }
			if(allowedCached){
				uni.setStorageSync('page_data',responseData)
			}
		   return responseData
		   
	   }
	   
    }).catch(parmas => {
		console.log(parmas)
		uni.reLaunch({
			url:setting.getErrorPage()+'?msg='+"服务器无法访问"+urlConfig
		})
		/**
		uni.showToast({
			title:"网络访问异常"+url,
			icon:'none',
			duration: 5000
		})
		*/
		uni.showModal({
			title:"网络访问异常"+url,
			content:parmas
		})

　　})
	if(allowedCached){
		return Promise.resolve (resultData)
	}
	return uniRequestData
 } 
 export default request